﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml.Linq;
using Windows.UI.Xaml.Media;
using AudioBooks.Data;
using Windows.ApplicationModel.DataTransfer;
using Windows.Foundation;
using Windows.Media;
using Windows.Networking.BackgroundTransfer;
using Windows.Storage;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Automation;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Navigation;
using Books.SQLite;
using System.Linq;
using Services.Model;
using AudioBooks.Controls;
using AudioBooks.SQLite;

// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234237

namespace AudioBooks.BookDetailsGroup
{
    /// <summary>
    /// A basic page that provides characteristics common to most applications.
    /// </summary>
    public sealed partial class BookDetailsOld : AudioBooks.Common.LayoutAwarePage
    {
        bool downloadedFile = false;
        private static int indexPlayFile;
        IReadOnlyList<StorageFile> FilesPlay;
        bool goBackedFlag = false;
        bool isdisable = false;
        private DispatcherTimer timer;

        private bool _sliderpressed = false;

        StorageFile nowPlaying;

        float count = 0;
        float total = 0;

        string selectedChapterName = "";

        public string nowPlayingChapter = "";

        ShareContent shareContent = new ShareContent();
        DataTransferManager dataTransferManager;

        Book newBook;

        SystemMediaTransportControls systemMediaControls = null;
        bool SystemMediaTransportControlsInitialized = false;
        public BookDetailsOld()
        {
            this.InitializeComponent();
            this.Loaded += BookDetails_Loaded;
            this.NavigationCacheMode = Windows.UI.Xaml.Navigation.NavigationCacheMode.Required;
        }

        void BookDetails_Loaded(object sender, RoutedEventArgs e)
        {
            DependencyObject rootGrid = VisualTreeHelper.GetChild(Window.Current.Content, 0);
            App.Player = (MediaElement)VisualTreeHelper.GetChild(rootGrid, 0);
            if (App.Player != null)
            {

                timelineSlider.ValueChanged += timelineSlider_ValueChanged;
                PointerEventHandler pointerpressedhandler = new PointerEventHandler(slider_PointerEntered);
                timelineSlider.AddHandler(Control.PointerPressedEvent, pointerpressedhandler, true);

                PointerEventHandler pointerreleasedhandler = new PointerEventHandler(slider_PointerCaptureLost);
                timelineSlider.AddHandler(Control.PointerCaptureLostEvent, pointerreleasedhandler, true);
                App.Player.CurrentStateChanged += mainPlayer_CurrentStateChanged;
                App.Player.MediaOpened += mainPlayer_MediaOpened;
                App.Player.MediaEnded += mainPlayer_MediaEnded;
                ShareContent();
            }

        }
        public async Task AddControl(StorageFile file)
        {
            App.NowPlayBookId = newBook.bookId;
            App.NowPlayChapterId = file.DisplayName.Replace(".mp3", "");
            statusTextBlock.Text = "Chapter " + App.NowPlayChapterId + " - " + App.NowPlayTitle;
            timer = new DispatcherTimer();
            if (file != null)
            {
                MediaPlaybackType mediaPlaybackType;
                if ((file.FileType == ".mp4") || (file.FileType == ".wmv"))
                {
                    mediaPlaybackType = MediaPlaybackType.Video;
                }
                else
                {
                    mediaPlaybackType = MediaPlaybackType.Music;
                }

                // Inform the system transport controls of the media information
                if (!(await systemMediaControls.DisplayUpdater.CopyFromFileAsync(mediaPlaybackType, file)))
                {
                    //  Problem extracting metadata- just clear everything
                    systemMediaControls.DisplayUpdater.ClearAll();
                }
                systemMediaControls.DisplayUpdater.Update();
            }
            var bookMarks = HandlePlayChapter.GetDataPlayChapterInfosByBookId(App.NowPlayBookId, App.NowPlayChapterId);
            if (bookMarks != null && bookMarks.Count > 0)
            {
                BookMarkView.Visibility = Visibility.Visible;
            }
            else
            {
                BookMarkView.Visibility = Visibility.Collapsed;
            }
            this.DefaultViewModel["Bookmarks"] = bookMarks;
            await SetMediaElementSourceAsync(file);
        }
        async void mainPlayer_MediaEnded(object sender, RoutedEventArgs e)
        {
            StopTimer();
            timelineSlider.Value = 0.0;
            await NextChapter();
        }

        void mainPlayer_MediaOpened(object sender, RoutedEventArgs e)
        {
            double absvalue = (int)Math.Round(App.Player.NaturalDuration.TimeSpan.TotalSeconds, MidpointRounding.AwayFromZero);
            timelineSlider.Maximum = absvalue;
            transportControlStackPanel.Visibility = Visibility.Visible;
            timelineSlider.StepFrequency = SliderFrequency(App.Player.NaturalDuration.TimeSpan);
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override async void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {

        }

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
        protected override void SaveState(Dictionary<String, Object> pageState)
        {

        }
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            systemMediaControls = SystemMediaTransportControls.GetForCurrentView();
            systemMediaControls.ButtonPressed += SystemMediaControls_ButtonPressed;
            systemMediaControls.IsPlayEnabled = true;
            systemMediaControls.IsPauseEnabled = true;
            systemMediaControls.IsStopEnabled = true;
            SystemMediaTransportControlsInitialized = true;
            var getbookId = (string)e.Parameter;
            if (App.BookIdSelect == getbookId)
                return;
            if (App.NowPlayBookId != getbookId)
            {
                NextButton.IsEnabled = false;
                PreviousButton.IsEnabled = false;
            }
            App.BookIdSelect = getbookId;
            var getBookDetail = await App.CallService.GetBookDetailAsync(App.BookIdSelect, string.Empty);
            if (getBookDetail != null && getBookDetail.book_detail != null)
            {
                if (getBookDetail.chapter_list.Count > 0)
                {
                    var listData = ManagerFilesDownloadComplete.GetDataDownLoadFiles();
                    foreach (var m in getBookDetail.chapter_list)
                    {
                        if (listData != null)
                        {
                            var getUrl = (new Uri(m.audio_link)).Segments; ;
                            var checkFilesExits = listData.FirstOrDefault(k => k.FileName == getUrl[getUrl.Length - 1] &&
                                k.BookId == App.BookIdSelect);
                            if (checkFilesExits != null)
                                m.isDownload = true;
                        }
                        else
                            m.isDownload = false;
                    }
                }
                newBook = new Book()
                {
                    title = getBookDetail.book_detail.book_name,
                    bookId = getBookDetail.book_detail.book_id,
                    shortDescrip = getBookDetail.book_detail.summary,
                    longDescript = getBookDetail.book_detail.summary,
                    price = "",
                    author = getBookDetail.book_detail.author,
                    publish_date = getBookDetail.book_detail.publish_date,
                    _imagePath = getBookDetail.book_detail.cover_link,
                };
                this.DefaultViewModel["Group"] = newBook;
                this.DefaultViewModel["Items"] = getBookDetail.chapter_list;
                App.NowPlayTitle = newBook.title;
                StaticData.bookImage = new Uri(getBookDetail.book_detail.cover_link);
                shareContent.bookName = getBookDetail.book_detail.book_name;
            }
        }
        /// <summary>
        /// Handler for the system transport controls button.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void SystemMediaControls_ButtonPressed(SystemMediaTransportControls sender, SystemMediaTransportControlsButtonPressedEventArgs e)
        {
            switch (e.Button)
            {
                case SystemMediaTransportControlsButton.Play:
                    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        App.Player.Play();
                    });
                    break;

                case SystemMediaTransportControlsButton.Pause:
                    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        App.Player.Pause();
                    });
                    break;

                case SystemMediaTransportControlsButton.Stop:
                    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        App.Player.Stop();
                    });
                    break;

                default:
                    break;
            }
        }

        private async Task<bool> CheckFileExisted(string source)
        {
            bool fileExisted;
            string[] b = source.Split('/');
            string folderName = b[b.Length - 2];
            string fileName = b[b.Length - 1];
            try
            {
                StorageFolder storageFolder = await ApplicationData.Current.LocalFolder.GetFolderAsync(folderName);
                StorageFile storageFile = await storageFolder.GetFileAsync(fileName);
                var content = await FileIO.ReadBufferAsync(storageFile);
                var numberOfBytes = content.Length;
                if (numberOfBytes != 0)
                {
                    fileExisted = true;
                }
                else
                {
                    fileExisted = false;
                }
                fileExisted = true;
            }
            catch
            {
                fileExisted = false;
            }
            return fileExisted;
        }

        #region Download Chapter

        string FormatTimeSpan(TimeSpan timeSpan)
        {
            var sb = new StringBuilder();

            if (timeSpan < TimeSpan.Zero)
            {
                sb.Append('-');

                timeSpan = -timeSpan;
            }

            if (timeSpan.Days > 1)
                sb.AppendFormat(timeSpan.ToString(@"%d\."));

            sb.Append(timeSpan.ToString(@"hh\:mm\:ss"));

            return sb.ToString();
        }
        #endregion

        #region Media Control



        private void PauseButton_Click(object sender, RoutedEventArgs e)
        {
            if (App.Player.CurrentState == Windows.UI.Xaml.Media.MediaElementState.Playing)
            {
                App.Player.Pause();
                MediaControl.IsPlaying = false;
                PauseButton.Content = "";
                AutomationProperties.SetName(PauseButton, "Resume");
                //  AutomationProperties.SetName(pausebuttonsnap, "Resume");
                // AutomationProperties.SetName(PauseButton1, "Resume");

            }
            else
            {
                App.Player.Play();
                MediaControl.IsPlaying = true;
                PauseButton.Content = "";
                AutomationProperties.SetName(PauseButton, "Pause");
            }

        }

        private void StopButton_Click(object sender, RoutedEventArgs e)
        {
            timelineSlider.Value = 0;
            App.Player.Stop();
            PauseButton.Content = "";
            AutomationProperties.SetName(PauseButton, "Pause");
        }

        private void timelineSlider_ValueChanged(object sender, Windows.UI.Xaml.Controls.Primitives.RangeBaseValueChangedEventArgs e)
        {
            Runtime.Text = FormatTimeSpan(App.Player.Position);
            //System.Diagnostics.Debug.WriteLine("Slider old value = {0} new value = {1}.", e.OldValue, e.NewValue);
            if (!_sliderpressed)
            {
                App.Player.Position = TimeSpan.FromSeconds(e.NewValue);
            }

            if (timelineSlider.Value == 99)
            {
                System.Diagnostics.Debug.WriteLine("Hello world");
            }
        }

        private double SliderFrequency(TimeSpan timevalue)
        {
            double stepfrequency = -1;

            double absvalue = (int)Math.Round(timevalue.TotalSeconds, MidpointRounding.AwayFromZero);
            stepfrequency = (int)(Math.Round(absvalue / 100));

            if (timevalue.TotalMinutes >= 10 && timevalue.TotalMinutes < 30)
            {
                stepfrequency = 10;
            }
            else if (timevalue.TotalMinutes >= 30 && timevalue.TotalMinutes < 60)
            {
                stepfrequency = 30;
            }
            else if (timevalue.TotalHours >= 1)
            {
                stepfrequency = 60;
            }

            if (stepfrequency == 0) stepfrequency += 1;

            if (stepfrequency == 1)
            {
                stepfrequency = absvalue / 100;
            }

            return stepfrequency;
        }

        private void SetupTimer()
        {
            if (timer != null)
                timer = null;
            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(1.0);
            timer.Tick += _timer_Tick;
            timer.Start();
        }

        private void _timer_Tick(object sender, object e)
        {
            if (!_sliderpressed)
            {
                timelineSlider.Value = App.Player.Position.TotalSeconds;
            }
        }
        private void StopTimer()
        {
            timer.Stop();
            timer.Tick -= _timer_Tick;
        }

        private async Task SetMediaElementSourceAsync(StorageFile file)
        {
            var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
            App.Player.SetSource(stream, file.ContentType);
            App.Player.Play();
            SetupTimer();
        }

        #endregion

        #region Media Control

        private async void MediaControl_StopPressed(object sender, object e)
        {
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                App.Player.Stop();
                MediaControl.IsPlaying = false;
            });
        }

        private async void MediaControl_PlayPauseTogglePressed(object sender, object e)
        {

            if (MediaControl.IsPlaying == true)
            {
                await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    App.Player.Pause();
                    MediaControl.IsPlaying = false;
                    PauseButton.Content = "";
                    AutomationProperties.SetName(PauseButton, "Resume");
                });
            }
            else
            {

                await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    App.Player.Play();
                    MediaControl.IsPlaying = true;
                    PauseButton.Content = "";
                    AutomationProperties.SetName(PauseButton, "Pause");
                    //AutomationProperties.SetName(pausebuttonsnap, "Pause");
                    // AutomationProperties.SetName(PauseButton1, "Pause");
                });
            }
        }

        private async void MediaControl_PausePressed(object sender, object e)
        {
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                App.Player.Pause();
                MediaControl.IsPlaying = false;
            });
        }

        private async void MediaControl_PlayPressed(object sender, object e)
        {
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                App.Player.Play();
                MediaControl.IsPlaying = true;
            });
        }

        void slider_PointerEntered(object sender, PointerRoutedEventArgs e)
        {
            System.Diagnostics.Debug.WriteLine("Pointer entered event fired");
            _sliderpressed = true;
        }

        void slider_PointerCaptureLost(object sender, PointerRoutedEventArgs e)
        {
            System.Diagnostics.Debug.WriteLine("Pointer capture lost event fired");
            System.Diagnostics.Debug.WriteLine("Slider value at capture lost {0}", timelineSlider.Value);
            //myMediaElement.PlaybackRate = 1;
            App.Player.Position = TimeSpan.FromSeconds(timelineSlider.Value);
            _sliderpressed = false;
        }

        #endregion
        private void GoBack(object sender, RoutedEventArgs e)
        {
            goBackedFlag = true;
            this.Frame.GoBack();
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            dataTransferManager.DataRequested -= new TypedEventHandler<DataTransferManager,
                DataRequestedEventArgs>(this.ShareTextHandler);
            App.Player.CurrentStateChanged -= mainPlayer_CurrentStateChanged;
            App.Player.MediaOpened -= mainPlayer_MediaOpened;
            App.Player.MediaEnded -= mainPlayer_MediaEnded;

            base.OnNavigatedFrom(e);
        }

        public void ShareContent()
        {
            dataTransferManager = DataTransferManager.GetForCurrentView();

            dataTransferManager.DataRequested += new TypedEventHandler<DataTransferManager,
                DataRequestedEventArgs>(this.ShareTextHandler);
        }

        public void ShareTextHandler(DataTransferManager sender, DataRequestedEventArgs e)
        {
            DataRequest request = e.Request;

            shareContent.message = "Listening to 'Tiger's Curse' Audiobook. Find 'Tiger's Curse' in windows 8 store and enjoy it with me";

            request.Data.Properties.Title = "Enjoying 'Tiger's Curse' Audiobook ";
            request.Data.Properties.Description = shareContent.bookName;
            request.Data.SetText(shareContent.message);
        }

        private void ForwardButton_Click(object sender, RoutedEventArgs e)
        {
            if (App.Player.Position < App.Player.NaturalDuration.TimeSpan.Add(new TimeSpan(0, -1, 0)))
            {
                App.Player.Position = App.Player.Position.Add(new TimeSpan(0, 1, 0));
            }

        }

        private void RewindButton_Click(object sender, RoutedEventArgs e)
        {

            if (App.Player.Position > new TimeSpan(0, 1, 0))
            {
                App.Player.Position = App.Player.Position.Add(new TimeSpan(0, -1, 0));
            }
            else
            {
                App.Player.Position = new TimeSpan(0);
            }
        }

        private void mainPlayer_CurrentStateChanged(object sender, RoutedEventArgs e)
        {
            if (App.Player.CurrentState == Windows.UI.Xaml.Media.MediaElementState.Paused)
            {
                PauseButton.Content = "";
                AutomationProperties.SetName(PauseButton, "Resume");
                PreviousButton.IsEnabled = true;
                NextButton.IsEnabled = true;
                RewindButton.IsEnabled = true;
                PauseButton.IsEnabled = true;
                ForwardButton.IsEnabled = true;
                StopButton.IsEnabled = true;
                timelineSlider.IsEnabled = true;
            }
            else
            {
                if (App.Player.CurrentState == Windows.UI.Xaml.Media.MediaElementState.Playing)
                {
                    PauseButton.Content = "";
                    AutomationProperties.SetName(PauseButton, "Pause");
                    ////AutomationProperties.SetName(pausebuttonsnap, "Pause");
                    // AutomationProperties.SetName(PauseButton1, "Pause");
                    RewindButton.IsEnabled = true;
                    ForwardButton.IsEnabled = true;
                    StopButton.IsEnabled = true;
                    PauseButton.IsEnabled = true;
                    PreviousButton.IsEnabled = true;
                    NextButton.IsEnabled = true;
                    timelineSlider.IsEnabled = true;
                    txtTotalTime.Text = FormatTimeSpan(App.Player.NaturalDuration.TimeSpan);
                }
                else
                {
                    PauseButton.Content = "";
                    AutomationProperties.SetName(PauseButton, "Resume");
                    //AutomationProperties.SetName(pausebuttonsnap, "Resume");
                    // AutomationProperties.SetName(PauseButton1, "Resume");
                    RewindButton.IsEnabled = false;
                    ForwardButton.IsEnabled = false;
                    PauseButton.IsEnabled = false;
                    StopButton.IsEnabled = false;
                    PreviousButton.IsEnabled = false;
                    NextButton.IsEnabled = false;
                    timelineSlider.IsEnabled = false;
                }


            }


        }
        private void DownloadAllFile(object sender, RoutedEventArgs e)
        {
            var listChapter = this.DefaultViewModel["Items"] as List<ChapterList>;
            if (listChapter.Count > 0)
            {
                foreach (var chapter in listChapter)
                {
                    if (!chapter.IsDownload)
                    {
                        var items = this.bookChapterListView.ContainerFromItem(chapter) as ListViewItem;
                        var getControl = items.ContentTemplateRoot as DownloadChapter;
                        var listChapterData = new List<ChapterList>();
                        listChapterData.Add(chapter);
                        getControl.DownloadAll.Execute(listChapterData);
                    }

                }
            }
            else
            {
                MessageDialog mesage = new MessageDialog("Chapter not found");
                mesage.ShowAsync();
            }
        }

        private async void selectItemChapter(object sender, ItemClickEventArgs e)
        {
            var itemSelect = e.ClickedItem as ChapterList;
            if (itemSelect.IsDownload)
            {
                var checkExitsFileDownloadComplete = ManagerFilesDownloadComplete.CheckExitsFolder(App.BookIdSelect);
                if (checkExitsFileDownloadComplete)
                {
                    var getFolder = await ApplicationData.Current.LocalFolder.GetFolderAsync(App.BookIdSelect);
                    var getListFile = await getFolder.GetFilesAsync();
                    if (getListFile.Count > 0)
                    {
                        indexPlayFile = int.Parse(itemSelect.chapter_no);
                        try
                        {
                            FilesPlay = getListFile;
                            var getItem = FilesPlay[indexPlayFile - 1];
                            await AddControl(getItem);
                        }
                        catch (Exception ex)
                        { return; }
                    }

                }
            }
            else
            {
                var items = this.bookChapterListView.ContainerFromItem(itemSelect) as ListViewItem;
                var getControl = items.ContentTemplateRoot as DownloadChapter;
                var listChapter = new List<ChapterList>();
                listChapter.Add(itemSelect);
                getControl.DownloadAll.Execute(listChapter);
            }
        }


        private async void NextButton_Click(object sender, RoutedEventArgs e)
        {
            await NextChapter();
        }

        private async Task NextChapter()
        {
            var getFolder = await ApplicationData.Current.LocalFolder.GetFolderAsync(App.BookIdSelect);
            var getListFile = await getFolder.GetFilesAsync();
            if (getListFile.Count > 0)
            {
                FilesPlay = getListFile;
                if (indexPlayFile < FilesPlay.Count)
                {
                    indexPlayFile++;
                    await AddControl(FilesPlay[indexPlayFile - 1]);
                }

                else
                {
                    MessageDialog message = new MessageDialog("End list chapter");
                    message.ShowAsync();
                }
            }
        }
        private async void PreviousButton_Click(object sender, RoutedEventArgs e)
        {
            var getFolder = await ApplicationData.Current.LocalFolder.GetFolderAsync(App.BookIdSelect);
            var getListFile = await getFolder.GetFilesAsync();
            if (getListFile.Count > 0)
            {
                FilesPlay = getListFile;
                if (indexPlayFile >= 2)
                {
                    indexPlayFile--;
                    await AddControl(FilesPlay[indexPlayFile - 1]);
                }

                else
                {
                    MessageDialog message = new MessageDialog("End list chapter");
                    message.ShowAsync();
                }

            }
        }

        private async void Image_Tapped(object sender, TappedRoutedEventArgs e)
        {
            var BookMark = new PlayChapterInfo()
            {
                BookId = App.BookIdSelect,
                Position = App.Player.Position,
                ChapterName = App.NowPlayChapterId
            };
            if (string.IsNullOrEmpty(BookMark.BookId) || string.IsNullOrEmpty(BookMark.ChapterName))
            {
                MessageDialog message = new MessageDialog("Please choose chapter before.");
                await message.ShowAsync();
                return;
            }
            HandlePlayChapter.SaveDataPlayChapterInfo(BookMark);
            BookMarkView.Visibility = Visibility.Visible;
            this.DefaultViewModel["Bookmarks"] = HandlePlayChapter.GetDataPlayChapterInfosByBookId(App.NowPlayBookId, App.NowPlayChapterId);
        }

        private void ListView_ItemClick(object sender, ItemClickEventArgs e)
        {
            var item = (PlayChapterInfo)e.ClickedItem;
            App.Player.Position = item.Position;
        }


    }
}